import threading
import queue
from datetime import datetime
from xbase_util.common_util import date2s


class TaskThreadManager:
    def __init__(self):
        self.task_queue = queue.Queue()
        self.threads_info = []
        self.manager_thread = threading.Thread(target=self._process_queue)
        self.stop_event = threading.Event()
        self.manager_thread.start()
        print("初始化:线程管理器")

    def _process_queue(self):
        while not self.stop_event.is_set():
            if not self.task_queue.empty():
                thread = self.task_queue.get()
                for info in self.threads_info:
                    if info["thread"] == thread:
                        info["is_running"] = True
                thread.start()
                thread.join()
                self.threads_info = [info for info in self.threads_info if info["thread"].is_alive()]

    def start_thread(self, target, *args, name=None):
        created_time = datetime.now()
        thread = threading.Thread(target=target, args=args, name=name, daemon=True)
        self.task_queue.put(thread)

        thread_info = {
            "thread": thread,
            "name": thread.name,
            "created_time": created_time,
            "thread_id": thread.ident,
            "is_running": False
        }
        self.threads_info.append(thread_info)

    def get_thread_status(self):
        status_list = []
        for info in self.threads_info:
            status = {
                "name": info["name"],
                "created_time": date2s(info["created_time"]),
                "is_alive": info["thread"].is_alive(),
                "is_running": info["is_running"]
            }
            status_list.append(status)
        return status_list

    def stop_manager(self):
        self.stop_event.set()
        self.manager_thread.join()
